//
//  VideoGestureView.swift
//  UILibrarysKit
//
//  Created by TSYH on 2024/5/31.
//

import Foundation
import MediaPlayer

public protocol VideoGestureViewDelegate : AnyObject {
    func swipeDownGesture()
}

public class VideoGestureView: UIView {
    
    weak var ownerPlayer: VideoPlayer?
    weak var delegate : VideoGestureViewDelegate?
    required init(ownerPlayer: VideoPlayer?) {
        super.init(frame: .zero)
        self.ownerPlayer = ownerPlayer
        initUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var panGesture: UIPanGestureRecognizer!
    var tapGesture: UITapGestureRecognizer!
    var doubleTapGesture: UITapGestureRecognizer!
    
    fileprivate var isSliderSliding = false
    fileprivate var isVolume        = false
    /// 滑动方向
    fileprivate var panDirection = BMPanDirection.horizontal
    
    // MARK: - 初始化
    fileprivate func initUI() {
        backgroundColor = UIColor.clear
        
        panGesture = UIPanGestureRecognizer(target: self, action: #selector(self.panDirection(_:)))
        addGestureRecognizer(panGesture)
        
        tapGesture = UITapGestureRecognizer(target: self, action: #selector(onTapGestureTapped(_:)))
        tapGesture.delegate = self
        addGestureRecognizer(tapGesture)
        
        doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(onDoubleTapGestureRecognized(_:)))
        doubleTapGesture.delegate = self
        doubleTapGesture.numberOfTapsRequired = 2
        addGestureRecognizer(doubleTapGesture)
            
        tapGesture.require(toFail: doubleTapGesture)
    }
    
    var isLock: Bool = false {
        didSet {
            panGesture.isEnabled = !isLock
            doubleTapGesture.isEnabled = !isLock
        }
    }
    
    // 系统音量视图
    var systermVolumeSlider: UISlider? {
        return MPVolumeView().subviews.first(where: { $0 is UISlider }) as? UISlider
    }
    
    @objc private func panDirection(_ pan: UIPanGestureRecognizer) {
        // 根据在view上Pan的位置，确定是调音量还是亮度
        let locationPoint = pan.location(in: self)
        
        // 我们要响应水平移动和垂直移动
        // 根据上次和本次移动的位置，算出一个速率的point
        let velocityPoint = pan.velocity(in: self)
        
        // 判断是垂直移动还是水平移动
        switch pan.state {
        case UIGestureRecognizer.State.began:
            // 使用绝对值来判断移动的方向
            let x = abs(velocityPoint.x)
            let y = abs(velocityPoint.y)
            
            if x > y {
                self.panDirection = BMPanDirection.horizontal
                ownerPlayer?.gestureView(self, horizontalMoved: 0, state: .began)
            } else {
                self.panDirection = BMPanDirection.vertical
                self.isVolume = locationPoint.x > self.bounds.size.width / 2
            }
            
        case UIGestureRecognizer.State.changed:
            switch self.panDirection {
            case BMPanDirection.horizontal:
                ownerPlayer?.gestureView(self, horizontalMoved: isLayoutRTL ? -velocityPoint.x : velocityPoint.x, state: .changed)
            case BMPanDirection.vertical:
                self.verticalMoved(velocityPoint.y)
            }
            
        case UIGestureRecognizer.State.ended:
            // 移动结束也需要判断垂直或者平移
            // 比如水平移动结束时，要快进到指定位置，如果这里没有判断，当我们调节音量完之后，会出现屏幕跳动的bug
            switch (self.panDirection) {
            case BMPanDirection.horizontal:
                ownerPlayer?.gestureView(self, horizontalMoved: 0, state: .ended)
            case BMPanDirection.vertical:
                self.isVolume = false
            }
        default:
            break
        }
    }
    
    // 阿语适配手势
    var isLayoutRTL: Bool {
        return semanticContentAttribute == .forceRightToLeft
    }
    
    fileprivate func verticalMoved(_ value: CGFloat) {
//        if BMPlayerConf.enableVolumeGestures && self.isVolume {
//            self.systermVolumeSlider?.value -= Float(value / 10000)
//        }
//        else if BMPlayerConf.enableBrightnessGestures && !self.isVolume{
//            UIScreen.main.brightness -= value / 10000
//        }
        print("value === \(value)")
        var flag = false
        if value > 0 && !flag{
            flag = true
            self.delegate?.swipeDownGesture()
        }
      
    }
    
    @objc private func onTapGestureTapped(_ gesture: UITapGestureRecognizer) {
        ownerPlayer?.gestureView(self, onTap: gesture)
    }
    
    @objc private func onDoubleTapGestureRecognized(_ gesture: UITapGestureRecognizer) {
        ownerPlayer?.togglePlay()
    }
}

extension VideoGestureView: UIGestureRecognizerDelegate {
    public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        if gestureRecognizer is UITapGestureRecognizer {
            if touch.view is UIControl {
                return false
            }
        }
        return true
    }
}
